<?php

namespace App\Http\Controllers\Admin\Blog;

use App\Blog;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class BlogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //dd($users);
        //获得所有文章数据，获取分页数据
        $blogs = Blog::paginate(10);
        //加载前端模板
        return view('admin.blog.index',compact('blogs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.blog.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //获得POST数据
        $post = $request->all();
        //dd($post);
        //获取当前已经登录的用户的数据
        $user = Auth::user();
        //将内容添加到数据库
        $user->blog()->create($post);
        //设置闪存信息
        session()->flash('success','文章发布成功！');
        //设置跳转
        return redirect(route('blog.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function show(Blog $blog)
    {
        //加载展示模板
        return view('admin.blog.show',compact('blog'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function edit(Blog $blog)
    {
        //通过策略权限判断是否有权限编辑文章内容
        $this->authorize('update',$blog);
        //加载博客编辑页模板
        return view('admin.blog.edit',compact('blog'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Blog $blog)
    {
        //替换保存标题信息
        $blog->title = $request->input('title');
        //替换保存文章内容信息
        $blog->content = $request->input('content');
        //将数据写入数据库
        $blog->save();
        //成功的闪存提示
        session()->flash('success','博客修改成功！');
        //跳转页面
        return redirect(route('blog.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function destroy(Blog $blog)
    {
        $blog->delete();
        session()->flash('success','博客内容已删除！');
        return back();
    }
}
